<?php

namespace App\Http\Controllers;

use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Http\Request;

class AdminController extends Controller
{
    //
    public function index()
    {
        if ($this->user->hasRole('超级管理员')) {
            $permissiontree = Permission::with(['allChildrenPermission' => function ($query) {
                $query->where('is_show', 1)->orderBy('sort');
            }])->where([['pid', 0], ['is_show', 1]])->orderBy('sort')->get(['id', 'display_name as text', 'icon'])->toArray();
        } else {
            $roles = array_column($this->user->roles()->get(['id'])->toArray(), 'id');
            $perms_id = \DB::table('permission_role')->whereIn('role_id', $roles)->pluck('permission_id')->toArray();

            $permissiontree = Permission::with(['allChildrenPermission' => function ($query) use ($perms_id) {
                $query->where('is_show', 1)->whereIn('id', $perms_id)->orderBy('sort');
            }])->where([['pid', 0], ['is_show', 1]])->orderBy('sort')->whereIn('id', $perms_id)->get(['id', 'display_name as text', 'icon'])->toArray();
        }
        $permissions = Permission::formatPermission($permissiontree);

        return view('admin.index', compact('permissions'));
    }

    public function main()
    {
        return view('admin.pages.main');
    }
}
